package com.ry.filter;


import com.ry.util.AddressUtils;
import com.ry.util.IpUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Component
public class CountFilter implements Filter {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    private String url;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.url = filterConfig.getInitParameter("URL");
        System.out.println("Filter init...");
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        String ip = IpUtils.getIpAddr(request);

        //访问路径
        String path = request.getRequestURI();
        path = path.substring(1,path.length());
        path = path.substring(path.indexOf("/"));

        //访问类型
        boolean isMobile = AddressUtils.judgeIsMoblie(request);

        System.out.println("ip: "+ip);
        System.out.println("路径: "+path);
        System.out.println("访问类型: "+(isMobile?"移动端":"PC端"));

        if(!path.contains("appStat")){
            redisTemplate.opsForValue().increment("visitCount");
        }

        filterChain.doFilter(req, resp);
    }

    @Override
    public void destroy() {
        System.out.println("Filter destory....");
    }
}
